package net.bingosoft.common.struts.tags;

import java.util.Iterator;

import javax.servlet.jsp.JspException;

import net.bingosoft.common.config.Config;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.taglib.TagUtils;
import org.apache.struts.taglib.html.TextareaTag;

/**
 * 2007-9-20 下午02:09:53
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:扩展textarea标签,设定默认最大长度、是否扩展验证错误及是否为必填项
 * ChangeLog:
 */
public class StrutsTextAreaTag extends TextareaTag {
	private static final long serialVersionUID = 1L;
	private boolean appendError = true;//是否扩展错误
	private boolean required = false; //该项是否为必填项
	private String defaultMaxLength = Config.getString("TEXTAREA.MAXLENGTH","1000");
	private String maxlength;
	private String dataType;
	private String message;
	
    public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getDataType() {
		return dataType;
	}
	public void setDataType(String dataType) {
		this.dataType = dataType;
		if("Required".equals(dataType)){
			this.required = true;
		}
	}
    
	
	/**
     * Generate an HTML &lt;textarea&gt; tag.
     * @throws JspException
     * @since Struts 1.1
     */
    protected String renderTextareaElement() throws JspException {
    	StringBuffer results = new StringBuffer();
		results.append(super.renderTextareaElement());
		//是否在text标签后面扩展对应的验证错误
		if(appendError){
			results = appendError(results);
		}
		if(required){
			results = appendRequiredFlag(results);
		}
		return results.toString();
    }
    
    /** Returns the onKeyDown event handler. */
    public String getOnkeyup() {
        return StringUtils.isEmpty(super.getOnkeyup())?"if(this.value.length >"+getMaxlength()+"){alert('输入内容超出最大长度["+getMaxlength()+"]限制');this.value=this.value.substring(0,"+getMaxlength()+");}":super.getOnkeyup();
    }
    

    /**
	 * @return the maxlength
	 */
	public String getMaxlength() {
		return StringUtils.isEmpty(maxlength)?defaultMaxLength:maxlength;
	}

	/**
     * 扩展对应的错误信息
     * @param results
     * @return
     * @throws JspException 
     */
    protected StringBuffer appendError(StringBuffer results) throws JspException{
    	ActionMessages errors = TagUtils.getInstance().getActionMessages(pageContext, Globals.ERROR_KEY);
		if (errors != null && !errors.isEmpty()) {
			String errorHeader = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"errors.header");
			String errorFooter = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"errors.footer");
			
			if(errorHeader == null){
				//struts验证出错信息前缀
				errorHeader ="<br/><font color='red'>";
			}
			if(errorHeader == null){
				//struts验证出错信息后缀
				errorFooter ="</font>";
			}
			
			Iterator it = errors.get(property);
			while(it.hasNext()){
				ActionMessage error = (ActionMessage)it.next();
				String errorMsg = "";
				if (error.isResource()) {
					errorMsg = TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,error.getKey(),error.getValues());
				} else {
					errorMsg = error.getKey();
				}
				results.append(errorHeader).append(errorMsg).append(errorFooter);
			}
		}
		return results;
    }
	/**
	 * 扩展必填项标志
	 * @param buffer
	 * @return
	 * @throws JspException
	 */
	private StringBuffer appendRequiredFlag(StringBuffer buffer) throws JspException{
		String requiredFlag =  TagUtils.getInstance().message(pageContext,Globals.MESSAGES_KEY,Globals.LOCALE_KEY,"flag.required");
		if(requiredFlag == null){
			requiredFlag = "<span style='color: red;vertical-align: middle;'> * </span>";
		}
		return buffer.append(requiredFlag);
	}
	/**
	 * @param appendError the appendError to set
	 */
	public void setAppendError(boolean appendError) {
		this.appendError = appendError;
	}
	/**
	 * @param defaultMaxLength the defaultMaxLength to set
	 */
	public void setDefaultMaxLength(String defaultMaxLength) {
		this.defaultMaxLength = defaultMaxLength;
	}
	/**
	 * @param maxlength the maxlength to set
	 */
	public void setMaxlength(String maxlength) {
		this.maxlength = maxlength;
	}
	/**
	 * @param required the required to set
	 */
	public void setRequired(boolean required) {
		this.required = required;
		if(this.required && this.dataType == null){
			this.dataType = "Required";
		}
	}
    /**
     * 'Hook' to enable tags to be extended and 
     *  additional attributes added.
     * @param handlers The StringBuffer that output will be appended to.
     */
    protected void prepareOtherAttributes(StringBuffer handlers) {
    	prepareAttribute(handlers, "Required", required); 
    	prepareAttribute(handlers, "DataType", dataType); 
    	prepareAttribute(handlers, "Message", message); 
    }

}
